﻿import { useState, useEffect, useCallback } from "react"
import { StorageManager, STORAGE_KEYS } from "./storage"

// 持久化状态Hook
export function usePersistentState<T>(
  key: string,
  defaultValue: T,
  options?: {
    autoSave?: boolean
    saveDelay?: number
  }
) {
  const [state, setState] = useState<T>(defaultValue)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const { autoSave = true, saveDelay = 1000 } = options || {}

  // 加载状态
  useEffect(() => {
    const loadState = async () => {
      try {
        setIsLoading(true)
        setError(null)
        const savedState = await StorageManager.get<T>(key, defaultValue)
        if (savedState !== null) {
          setState(savedState)
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : "加载状态失败")
        console.error(`加载持久化状态失败 (${key}):`, err)
      } finally {
        setIsLoading(false)
      }
    }

    loadState()
  }, [key, defaultValue])

  // 保存状态
  const saveState = useCallback(async (newState: T) => {
    try {
      setError(null)
      const success = await StorageManager.set(key, newState)
      if (!success) {
        throw new Error("保存状态失败")
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "保存状态失败")
      console.error(`保存持久化状态失败 (${key}):`, err)
    }
  }, [key])

  // 自动保存
  useEffect(() => {
    if (!autoSave || isLoading) return

    const timeoutId = setTimeout(() => {
      saveState(state)
    }, saveDelay)

    return () => clearTimeout(timeoutId)
  }, [state, autoSave, saveDelay, saveState, isLoading])

  // 手动保存
  const persistState = useCallback(async (newState?: T) => {
    const stateToSave = newState !== undefined ? newState : state
    await saveState(stateToSave)
  }, [state, saveState])

  // 更新状态
  const updateState = useCallback((newState: T | ((prev: T) => T)) => {
    setState(prev => {
      const updated = typeof newState === "function" ? (newState as (prev: T) => T)(prev) : newState
      return updated
    })
  }, [])

  // 重置状态
  const resetState = useCallback(async () => {
    setState(defaultValue)
    await StorageManager.remove(key)
  }, [defaultValue, key])

  return {
    state,
    setState: updateState,
    persistState,
    resetState,
    isLoading,
    error
  }
}

// 截屏状态Hook
export function useScreenshotState() {
  const [screenshots, setScreenshots] = useState<Array<{
    id: string
    dataUrl: string
    timestamp: number
    name?: string
  }>>([])
  const [isLoading, setIsLoading] = useState(true)

  // 加载截屏列表
  const loadScreenshots = useCallback(async () => {
    try {
      setIsLoading(true)
      const { ScreenshotStorage } = await import("./storage")
      const savedScreenshots = await ScreenshotStorage.getScreenshots()
      setScreenshots(savedScreenshots || [])
    } catch (error) {
      console.error("加载截屏列表失败:", error)
      setScreenshots([])
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 保存截屏
  const saveScreenshot = useCallback(async (screenshot: {
    id: string
    dataUrl: string
    timestamp: number
    name?: string
  }) => {
    try {
      const { ScreenshotStorage } = await import("./storage")
      await ScreenshotStorage.saveScreenshot(screenshot)
      setScreenshots(prev => [screenshot, ...prev.slice(0, 49)]) // 限制最多50张
    } catch (error) {
      console.error("保存截屏失败:", error)
    }
  }, [])

  // 删除截屏
  const deleteScreenshot = useCallback(async (id: string) => {
    try {
      const { ScreenshotStorage } = await import("./storage")
      await ScreenshotStorage.deleteScreenshot(id)
      setScreenshots(prev => prev.filter(s => s.id !== id))
    } catch (error) {
      console.error("删除截屏失败:", error)
    }
  }, [])

  // 清空截屏
  const clearScreenshots = useCallback(async () => {
    try {
      const { ScreenshotStorage } = await import("./storage")
      await ScreenshotStorage.clearScreenshots()
      setScreenshots([])
    } catch (error) {
      console.error("清空截屏失败:", error)
    }
  }, [])

  useEffect(() => {
    loadScreenshots()
  }, [loadScreenshots])

  return {
    screenshots,
    isLoading,
    saveScreenshot,
    deleteScreenshot,
    clearScreenshots,
    refreshScreenshots: loadScreenshots
  }
}

// 定时器状态Hook
export function useTimerState() {
  const [timers, setTimers] = useState<Array<{
    id: string
    name: string
    duration: number
    remaining: number
    isRunning: boolean
    isCompleted: boolean
    createdAt: string
  }>>([])
  const [isLoading, setIsLoading] = useState(true)

  // 加载定时器列表
  const loadTimers = useCallback(async () => {
    try {
      setIsLoading(true)
      const { TimerStorage } = await import("./storage")
      const savedTimers = await TimerStorage.getTimers()
      setTimers(savedTimers || [])
    } catch (error) {
      console.error("加载定时器列表失败:", error)
      setTimers([])
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 保存定时器列表
  const saveTimers = useCallback(async (newTimers: typeof timers) => {
    try {
      const { TimerStorage } = await import("./storage")
      await TimerStorage.saveTimers(newTimers)
      setTimers(newTimers)
    } catch (error) {
      console.error("保存定时器列表失败:", error)
    }
  }, [])

  useEffect(() => {
    loadTimers()
  }, [loadTimers])

  return {
    timers,
    isLoading,
    saveTimers,
    refreshTimers: loadTimers
  }
}

// 编辑器状态Hook
export function useEditorState() {
  const [content, setContent] = useState("")
  const [isLoading, setIsLoading] = useState(true)

  // 加载编辑器内容
  const loadContent = useCallback(async () => {
    try {
      setIsLoading(true)
      const { EditorStorage } = await import("./storage")
      const savedContent = await EditorStorage.getContent()
      setContent(savedContent || "")
    } catch (error) {
      console.error("加载编辑器内容失败:", error)
      setContent("")
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 保存编辑器内容
  const saveContent = useCallback(async (newContent: string) => {
    try {
      const { EditorStorage } = await import("./storage")
      await EditorStorage.saveContent(newContent || "")
      setContent(newContent || "")
    } catch (error) {
      console.error("保存编辑器内容失败:", error)
    }
  }, [])

  // 自动保存
  useEffect(() => {
    if (isLoading) return

    const timeoutId = setTimeout(() => {
      saveContent(content)
    }, 2000) // 2秒后自动保存

    return () => clearTimeout(timeoutId)
  }, [content, saveContent, isLoading])

  useEffect(() => {
    loadContent()
  }, [loadContent])

  return {
    content,
    setContent,
    saveContent,
    isLoading,
    refreshContent: loadContent
  }
}

// 录屏状态Hook
export function useRecordingState() {
  const [recordings, setRecordings] = useState<Array<{
    id: string
    name: string
    dataUrl: string
    timestamp: number
    duration: number
  }>>([])
  const [isLoading, setIsLoading] = useState(true)
  const [currentRecording, setCurrentRecording] = useState<{
    id: string
    name: string
    dataUrl: string
    timestamp: number
    duration: number
  } | null>(null)

  // 加载录屏列表
  const loadRecordings = useCallback(async () => {
    try {
      setIsLoading(true)
      const { RecordingStorage } = await import("./storage")
      const savedRecordings = await RecordingStorage.getRecordings()
      setRecordings(savedRecordings || [])
    } catch (error) {
      console.error("加载录屏列表失败:", error)
      setRecordings([])
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 保存录屏
  const saveRecording = useCallback(async (recording: {
    id: string
    name: string
    dataUrl: string
    timestamp: number
    duration: number
  }) => {
    try {
      const { RecordingStorage } = await import("./storage")
      const recordings = await RecordingStorage.getRecordings()
      recordings.unshift(recording)
      
      // 限制最多保存20个录屏
      if (recordings.length > 20) {
        recordings.splice(20)
      }
      
      await RecordingStorage.saveRecordings(recordings)
      setRecordings(recordings)
      setCurrentRecording(recording)
    } catch (error) {
      console.error("保存录屏失败:", error)
    }
  }, [])

  // 删除录屏
  const deleteRecording = useCallback(async (id: string) => {
    try {
      const { RecordingStorage } = await import("./storage")
      const recordings = await RecordingStorage.getRecordings()
      const filtered = recordings.filter(r => r.id !== id)
      await RecordingStorage.saveRecordings(filtered)
      setRecordings(filtered)
      
      // 如果删除的是当前录屏，清空当前录屏
      if (currentRecording?.id === id) {
        setCurrentRecording(null)
      }
    } catch (error) {
      console.error("删除录屏失败:", error)
    }
  }, [currentRecording])

  // 清空录屏
  const clearRecordings = useCallback(async () => {
    try {
      const { RecordingStorage } = await import("./storage")
      await RecordingStorage.saveRecordings([])
      setRecordings([])
      setCurrentRecording(null)
    } catch (error) {
      console.error("清空录屏失败:", error)
    }
  }, [])

  // 获取录屏设置
  const getRecordingSettings = useCallback(async () => {
    try {
      const { RecordingStorage } = await import("./storage")
      return await RecordingStorage.getRecordingSettings()
    } catch (error) {
      console.error("获取录屏设置失败:", error)
      return {
        quality: "high",
        format: "webm",
        maxDuration: 300
      }
    }
  }, [])

  // 保存录屏设置
  const saveRecordingSettings = useCallback(async (settings: {
    quality: string
    format: string
    maxDuration: number
  }) => {
    try {
      const { RecordingStorage } = await import("./storage")
      await RecordingStorage.saveRecordingSettings(settings)
    } catch (error) {
      console.error("保存录屏设置失败:", error)
    }
  }, [])

  useEffect(() => {
    loadRecordings()
  }, [loadRecordings])

  return {
    recordings,
    currentRecording,
    setCurrentRecording,
    isLoading,
    saveRecording,
    deleteRecording,
    clearRecordings,
    getRecordingSettings,
    saveRecordingSettings,
    refreshRecordings: loadRecordings
  }
}
